#! /bin/sh
#       Licensed to the Apache Software Foundation (ASF) under one
#       or more contributor license agreements.  See the NOTICE file
#       distributed with this work for additional information
#       regarding copyright ownership.  The ASF licenses this file
#       to you under the Apache License, Version 2.0 (the
#       "License"); you may not use this file except in compliance
#       with the License.  You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#       Unless required by applicable law or agreed to in writing,
#       software distributed under the License is distributed on an
#       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#       KIND, either express or implied.  See the License for the
#       specific language governing permissions and limitations
#       under the License.

ANT=$(which ant)

if [ "$1" == "-h" -o "$1" == "-help" ]
then
  echo 'usage: addWebworks'
  echo 'Automatically adds the webworks.js reference to all of your html files in the www/ folder'
  echo 'Only relevant to qnx'
  exit 0
fi

# cleanup after exit and/or on error
function on_exit {
    echo "\nDone!"
    echo "Remember to build your qnx project to get the webworks.js file in your js directory!\n"
}

function on_error {
    echo "An error occured."
}

# we do not want the script to silently fail
trap on_error ERR
trap on_exit EXIT

echo "Finding files to add webworks to... \n"

find www -name \*.html\* | while read fullpath
do
    if grep "webworks.js" $fullpath > /dev/null
    then
        echo "SKIPPING: "$fullpath
    else
        # i hate regex
        jspath=$( dirname "$fullpath" ) ; jspath=${jspath#./www} ; jspath=${jspath//\/[a-zA-Z0-9]/../} ; jspath=${jspath//[a-zA-Z0-9]/}
        sed -i "" '/<head>/ a\
        <script type="text/javascript" src="'$jspath'js/webworks.js"></script>' $fullpath  
        echo "ADDING: "$fullpath
    fi
done
